package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crm.mapper.RoleMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.mapper.UserMapper;
import com.crm.pojo.common.ErrorMessage;
import com.crm.pojo.common.PageResult;
import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.User;
import com.crm.pojo.dto.LoginDto;
import com.crm.pojo.dto.RoleDto;
import com.crm.pojo.dto.UserDto;
import com.crm.pojo.vo.RoleVo;
import com.crm.pojo.vo.TransferUserVo;
import com.crm.pojo.vo.UserRoleVo;
import com.crm.pojo.vo.UserVo;
import com.crm.service.UserService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author
 * @version 1.0
 * @description:
 * @date 2021/3/31 11:41
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User getLoginUser(LoginDto loginDto) {
        return userMapper.getLoginUser(loginDto);
    }

    @Override
    public PageResult list(UserDto userDto) {
        PageHelper.startPage(userDto.getPageNum(), userDto.getPageSize());
        List<UserVo> userVos = userMapper.list(userDto);
        com.github.pagehelper.Page page = (com.github.pagehelper.Page) userVos;
        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(userVos);
        return pageResult;
    }


    @Override
    public UserRoleVo userRoleVo() {
        UserRoleVo userRoleVo = new UserRoleVo();
        RoleDto roleDto = new RoleDto();
        List<RoleVo> roleVos = roleMapper.list(roleDto);
        userRoleVo.setRoles(roleVos);
        return userRoleVo;
    }

    @Override
    @Transactional
    public void add(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setCreateBy(UserContext.getCurrentUser().getUserName());
        user.setCreateTime(LocalDateTime.now());
        user.setPassword("123456"); // 使用默认密码
        userMapper.add(user);
        Long userId = user.getUserId();
        List<Integer> roleIds = userDto.getRoleIds();
        if (CollectionUtils.isEmpty(roleIds)) {
            throw new RuntimeException(ErrorMessage.USER_ERROR_MESSAGE_ADD_002);
        }
        if (!CollectionUtils.isEmpty(roleIds)) {
            userMapper.addUserRole(userId, roleIds);
        }

    }

    @Override
    public PageResult transferList(UserDto dto) {
        log.info("前端传入:{}", dto);
        Map<String, String> params = dto.getParams();
        LocalDateTime beginTime = null;
        LocalDateTime endTime = null;
        if (!CollectionUtils.isEmpty(params)) {
            String beginStr = params.get("beginTime");
            String endStr = params.get("endTime");
            if (StringUtils.hasText(beginStr) && StringUtils.hasText(endStr)) {
                beginTime = LocalDate.parse(beginStr).atStartOfDay();
                endTime = LocalDate.parse(endStr).atTime(23, 59, 59);
            }
        }
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        Long total = userMapper.count(dto.getPhonenumber(), dto.getUserName(), dto.getBeginTime(), dto.getEndTime());
        Integer startNum = (int) (total - 1) / pageSize;

        List<TransferUserVo> pageUsers = userMapper.selectTransfer(startNum, pageSize, dto.getPhonenumber(), dto.getUserName(), beginTime, endTime);
      /*  pageUsers.forEach(d->{
            d.setClueNum(0);
            d.setBusinessNum(0);
        });*/
        PageResult pageResult = new PageResult<>();
        pageResult.setCode(200);
        pageResult.setRows(pageUsers);
        pageResult.setMsg("查询成功");
        pageResult.setTotal(total);
        pageResult.setParams(null);
        return pageResult;
    }

    //查找某部门下有哪些用户
    @Override
    public List listSelect(Long deptId) {
        UserDto userDto = new UserDto();
        userDto.setDeptId(deptId);
        return userMapper.list(userDto);
    }

    //通过userName查询用户
    @Override
    public User getUserByUserName(String username) {
        return userMapper.getUserByUserName(username);
    }

    //通过userId查询用户
    @Override
    public User getUserById(Integer userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, userId);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 删除用户
     *
     * @param userId
     */
    @Override
    @Transactional
    public void del(Integer userId) {
        userMapper.del(userId);
        userMapper.delRole(userId);
    }
}